<template>
  <div class="shift-change-request">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <!-- 原班次信息 -->
      <div class="original-shift">
        <h5>原班次信息</h5>
        <div class="shift-info">
          <div class="info-item">
            <label>日期：</label>
            <span>{{ formatDate(shiftData.date) }}</span>
          </div>
          <div class="info-item">
            <label>时间：</label>
            <span>{{ shiftData.time }}</span>
          </div>
          <div class="info-item">
            <label>地点：</label>
            <span>{{ shiftData.location }}</span>
          </div>
        </div>
      </div>
      

      <!-- 调班信息 -->
      <el-form-item label="调班类型" prop="changeType">
        <el-radio-group v-model="formData.changeType">
          <el-radio label="swap">与其他医生调换</el-radio>
          <el-radio label="cancel">申请取消班次</el-radio>
          <el-radio label="other">其他</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="formData.changeType === 'swap'" label="调班医生" prop="targetDoctor">
        <el-select
          v-model="formData.targetDoctor"
          placeholder="请选择调班医生"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="doctor in availableDoctors"
            :key="doctor.id"
            :label="`${doctor.name} (${doctor.department})`"
            :value="doctor.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="formData.changeType === 'swap'" label="目标班次" prop="targetShift">
        <el-select
          v-model="formData.targetShift"
          placeholder="请选择目标班次"
          style="width: 100%"
        >
          <el-option
            v-for="shift in targetShifts"
            :key="shift.id"
            :label="getShiftLabel(shift)"
            :value="shift.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="申请原因" prop="reason">
        <el-input
          v-model="formData.reason"
          type="textarea"
          :rows="4"
          placeholder="请详细说明调班原因"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="紧急程度" prop="urgency">
        <el-radio-group v-model="formData.urgency">
          <el-radio label="low">一般</el-radio>
          <el-radio label="medium">重要</el-radio>
          <el-radio label="high">紧急</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="证明材料" prop="attachments">
        <el-upload
          v-model:file-list="formData.attachments"
          action="#"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
        >
          <el-button type="primary">
            <el-icon><Upload /></el-icon>
            上传文件
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持jpg、png、pdf格式文件，单个文件不超过5MB
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="联系方式" prop="contact">
        <el-input
          v-model="formData.contact"
          placeholder="请输入联系电话"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        提交申请
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'

const props = defineProps({
  shiftData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['submitted', 'cancel'])

// 响应式数据
const formRef = ref()
const submitting = ref(false)

// 表单数据
const formData = reactive({
  changeType: 'swap',
  targetDoctor: null,
  targetShift: null,
  reason: '',
  urgency: 'medium',
  attachments: [],
  contact: ''
})

// 验证规则
const formRules = {
  changeType: [
    { required: true, message: '请选择调班类型', trigger: 'change' }
  ],
  targetDoctor: [
    { 
      required: true, 
      message: '请选择调班医生', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (formData.changeType === 'swap' && !value) {
          callback(new Error('请选择调班医生'))
        } else {
          callback()
        }
      }
    }
  ],
  targetShift: [
    {
      required: true,
      message: '请选择目标班次',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (formData.changeType === 'swap' && !value) {
          callback(new Error('请选择目标班次'))
        } else {
          callback()
        }
      }
    }
  ],
  reason: [
    { required: true, message: '请输入申请原因', trigger: 'blur' },
    { min: 10, message: '申请原因至少10个字符', trigger: 'blur' }
  ],
  urgency: [
    { required: true, message: '请选择紧急程度', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 模拟数据
const availableDoctors = ref([
  { id: 1, name: '王医生', department: '内科' },
  { id: 2, name: '李医生', department: '内科' },
  { id: 3, name: '赵医生', department: '内科' },
  { id: 4, name: '刘医生', department: '外科' }
])

const targetShifts = computed(() => {
  if (!formData.targetDoctor) return []
  
  // 模拟获取目标医生的可用班次
  return [
    {
      id: 101,
      date: '2024-03-22',
      time: '08:00-12:00',
      location: '门诊部2诊室',
      type: 'morning'
    },
    {
      id: 102,
      date: '2024-03-23',
      time: '14:00-18:00',
      location: '门诊部1诊室',
      type: 'afternoon'
    },
    {
      id: 103,
      date: '2024-03-24',
      time: '18:00-22:00',
      location: '急诊科',
      type: 'night'
    }
  ]
})

// 方法
const getShiftLabel = (shift) => {
  return `${formatDate(shift.date)} ${shift.time} ${shift.location}`
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    weekday: 'short'
  })
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传3个文件')
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isPDF = file.type === 'application/pdf'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPG && !isPNG && !isPDF) {
    ElMessage.error('只能上传JPG、PNG或PDF格式的文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB!')
    return false
  }
  return true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // TODO: 调用API提交调班申请
    // await scheduleApi.submitChangeRequest({
    //   shiftId: props.shiftData.id,
    //   ...formData
    // })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('调班申请提交成功')
    emit('submitted')
  } catch (error) {
    if (error && error.fields) {
      ElMessage.warning('请完善表单信息')
    } else {
      ElMessage.error('提交失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  ElMessageBox.confirm(
    '确定要取消调班申请吗？已填写的信息将不会保存。',
    '确认取消',
    {
      confirmButtonText: '确定',
      cancelButtonText: '继续编辑',
      type: 'warning'
    }
  ).then(() => {
    emit('cancel')
  }).catch(() => {
    // 用户选择继续编辑
  })
}
</script>

<style lang="scss" scoped>
.shift-change-request {
  .original-shift {
    margin-bottom: 24px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 6px;

    h5 {
      margin: 0 0 12px 0;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }

    .shift-info {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;

      .info-item {
        display: flex;
        align-items: center;

        label {
          font-weight: 500;
          color: #606266;
          min-width: 50px;
          margin-right: 8px;
        }

        span {
          color: #303133;
        }
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
  }
}

@media (max-width: 768px) {
  .shift-change-request {
    .original-shift .shift-info {
      grid-template-columns: 1fr;
    }
  }
}
</style>